package cn.wolfcode.shop.mq;

import cn.wolfcode.shop.result.CodeMsg;
import cn.wolfcode.shop.service.ISeckillService;
import cn.wolfcode.shop.service.IWebSocketService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Component;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;

@Component
public class MQReceiver {
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private ISeckillService seckillService;
    @Autowired
    private MQSender mqSender;

    /**
     * 监听指定的订单消息中心队列 产生的消息
     * @param message  推送来的消息
     * @throws JMSException
     */
    @JmsListener(destination = MQDestination.ORDER_DESTINATION,containerFactory = "queueListenerFactory")
    public void receiveOrderMessage(Message message) throws JMSException {
        if (message instanceof ObjectMessage) {
            ObjectMessage objectMessage = (ObjectMessage) message;
            OrderMessage orderMessage = (OrderMessage) objectMessage.getObject();;
            try {

                String orderNo = seckillService.doSeckill(orderMessage.getUserId(), orderMessage.getGoodId());
                //webSocketService.sendMsg(orderMessage.getUuid(), CodeMsg.SUCCESS.fillArgs(orderNo));
                //秒杀操作成功后,发送消息到消息中心 内容未 需要返回给用户的订单号等信息,返回给哪个用户的webscoket(uuid)
                mqSender.sendWebSocketMessage(orderMessage.getUuid(), CodeMsg.SUCCESS.fillArgs(orderNo));
            } catch (Exception e) {
                //秒杀操作出现异常,说明秒杀失败,而redis中的库存已经减少了 需要进行库存的回补
                //使用异步处理的方式(activeMq消息中心)将失败后,库存回补需要的信息发送到消息中心
                mqSender.sendOrderDQL(orderMessage);
                e.printStackTrace();
            }
        }
    }

    /**
     * 监听消息中心存放订单处理失败消息的队列
     * @param message 推送来的消息
     */
    @JmsListener(destination = MQDestination.ORDER_DQL_DESTINATION,containerFactory = "queueListenerFactory")
    public void receiverOrderDQL(Message message) throws JMSException {
        if(message instanceof ObjectMessage){
            ObjectMessage objectMessage = (ObjectMessage) message;
            OrderMessage orderMessage = (OrderMessage) objectMessage.getObject();
            //同步redis 等于数据库库存,如果还有库存 同时发布更新本机标记的消息
            seckillService.syncStock(orderMessage.getGoodId());
            mqSender.sendWebSocketMessage(orderMessage.getUuid(),CodeMsg.SECKILL_FAILED);
        }
    }

}
